package com.marcosnobrega.android.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.marcosnobrega.android.bean.UsersListItem;
import com.marcosnobrega.android.threadservice.CheckMessagesThread;
import com.marcosnobrega.android.threadservice.PresenceThread;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.System;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Conversation extends Activity{
	
	private String myAndroidId;
	private ArrayAdapter<String> messages;
	private UsersListItem userTo;
	private EditText messageField;
	private Handler mHandler = new Handler();
	private Runnable mHanlderRunnable = new Runnable() {
		
		@Override
		public void run() {
			loadMessages();
		}
	};
	private Dialog mDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.conversation);
		
		this.userTo = (UsersListItem) getIntent().getExtras().get("userTo");
		this.messages = new ArrayAdapter<String>(this,R.layout.messageslist);
		this.messageField = (EditText)findViewById(R.id.sendMessageConversation);
		
		TextView labelTv = (TextView) findViewById(R.id.labelTvConversation);
		labelTv.setText("Conversando com "+this.userTo.getNickname());
		
		loadMessages();
		
		ListView messagesView = (ListView) findViewById(R.id.listViewConversation);
		messagesView.setAdapter(messages);
		
		Button btnSendMessage = (Button)findViewById(R.id.sendButtonConversation);
		btnSendMessage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Conversation.this.mandarMensagem(messageField.getText().toString(),userTo.getAndroid_id());
				messageField.setText("");
				loadMessages();
			}
		});
		
		myAndroidId = System.getString(getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);
		new Thread(CheckMessagesThread.getInstance(this.messages.getCount(), myAndroidId, mHandler, mHanlderRunnable)).start();
	}
	
	private void loadMessages(){
		
		HttpPost request = new HttpPost(AndroidNetwork.SERVICE_URL+"?action="+AndroidNetwork.ACTION_LIST_MESSAGES);
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("userAndroidId", myAndroidId));
		
		DefaultHttpClient client = new DefaultHttpClient();
		try {
			request.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			String responseText = EntityUtils.toString(entity);
			messages.clear();
			if(!responseText.equalsIgnoreCase("")){
				String[] jsonStrings = responseText.split(";;;");
				for(String s : jsonStrings){
					String[] mensagem = s.split(",");
					messages.add(mensagem[0]+" - "+mensagem[1]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void mandarMensagem(String mensagem, String userAndroidId){
		DefaultHttpClient client = new DefaultHttpClient();
    	
        HttpPost post = new HttpPost(AndroidNetwork.SERVICE_URL+"?action="+AndroidNetwork.ACTION_POST_MESSAGE);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("mensagem", mensagem));
        list.add(new BasicNameValuePair("userAndroidId",userAndroidId));
        list.add(
        		new BasicNameValuePair(
        				"remetenteAndroidId",
        				myAndroidId
        			)
        		);
        
        try {
        	post.setEntity(new UrlEncodedFormEntity(list));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			Toast.makeText(getApplicationContext(), EntityUtils.toString(entity), Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
			case R.id.menu_list_users:
				break;
				
			case R.id.settings:
				break;
				
			case R.id.menu_home:
				Intent homeIntent = new Intent(this, UserList.class);
				this.startActivity(homeIntent);
				break;
				
			case R.id.menu_change_nickname:
				Builder builder = new AlertDialog.Builder(this);
				builder.setIcon(R.drawable.euandroid);
				builder.setTitle(R.string.enternickname);
				EditText nicknameField = new EditText(this);
				nicknameField.setText(R.string.empty);
				nicknameField.setId(1853);
				builder.setView(nicknameField);
				builder.setPositiveButton(R.string.btnConfirmar, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String nickname=((EditText)mDialog.findViewById(1853)).getText().toString();
						new Thread(PresenceThread.getInstance(myAndroidId, nickname)).start();
					}
				});
				mDialog = builder.create();
				mDialog.show();
				break;

			default:
				Toast.makeText(this, "Função não implementada ainda!", Toast.LENGTH_LONG).show();
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater mInflater = getMenuInflater();
        mInflater.inflate(R.menu.main_menu, menu);
        return true;
	}

}
